package com.nd.bdc.presto.connection;

import com.nd.bdc.presto.util.ResourceFileLocator;
import io.prestosql.jdbc.PrestoConnection;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * <p>Description:  presto的jdbc连接</p>
 *
 * @author ggh
 * @date 2020/6/4
 */
@Component
public class PrestoConnProvider {
    public PrestoConnection getSSLConnection(String driver, String url, String username, String password, String ssLKeyStorePassword, String ssLKeyStorePath)throws ClassNotFoundException, SQLException {
        PrestoConnection connection;
        Class.forName(driver);

        String sslTrustStorePath = "." + ssLKeyStorePath;
        // 将SSLTrustStore文件从resource下copy到jar的同目录
        File desPath = new File(sslTrustStorePath);
        if(!desPath.exists()){
            ResourceFileLocator.copyFile(ssLKeyStorePath,desPath);
        }
//        URL resource = getClass().getClassLoader().getResource(ssLKeyStorePath);
        Properties properties = new Properties();
        properties.setProperty("SSL","true");
        properties.setProperty("user",username);
        properties.setProperty("password",password);
        if (desPath.exists()){
//            String jksPath = resource.getFile();
            properties.setProperty("SSLKeyStorePath", sslTrustStorePath);
            properties.setProperty("SSLKeyStorePassword",ssLKeyStorePassword);
        }

        connection = DriverManager.getConnection(url,properties).unwrap(PrestoConnection.class);

        return connection;
    }

    public PrestoConnection getConnection(String driver, String url, String username)throws ClassNotFoundException, SQLException {
        PrestoConnection connection;
        Class.forName(driver);
        Properties properties = new Properties();
        properties.setProperty("user",username);
        connection = DriverManager.getConnection(url,properties).unwrap(PrestoConnection.class);

        return connection;
    }
}
